<template>
  <div>
    <van-nav-bar title="登录" />

    <van-form @submit="login">
      <van-field
        v-model="mobile"
        required
        center
        clearable
        label="手机号"
        placeholder="18817345672"
        :rules="rules.mobile"
      />
      <van-field
        v-model="code"
        required
        label="验证码"
        placeholder="246810"
        :rules="rules.code"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLoad"
          :loading="isLoad"
          loading-text="登录中..."
        >
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
// import axios from '@/utils/request'
import { userLogin } from '@/api/user'
// import { Toast } from 'vant'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data() {
    return {
      mobile: '',
      code: '',
      // 是否在发送请求
      isLoad: false,
      rules: {
        mobile: [
          { required: true, message: '手机号不能为空' },
          {
            pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message: '手机号码格式错误'
          }
        ],
        code: [
          { required: true, message: '验证码不能为空' },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误'
          }
        ]
      }
    }
  },
  methods: {
    ...mapMutations('user', ['setToken']),
    async login() {
      this.isLoad = true
      try {
        // --------------------------------------封装前
        // async login() {
        //   console.log('登录了....')
        //   const res = await axios({
        //     method: 'POST',
        //     url: '/v1_0/authorizations',
        //     data: {
        //       mobile: this.mobile,
        //       code: this.code
        //     }
        //   })
        //   console.log(res)
        // }
        // --------------------------------------封装后
        const res = await userLogin(this.mobile, this.code)
        // console.log(res)

        // 保存token
        // this.$store.commit('setToken', res.data)

        // 之前：把token保存给本地存储
        // localStorage.setItem('token', JSON.stringify(res.data))
        // 现在需要把token存vuex中
        // this.$store.commit('user/setToken', res.data)

        // 使用辅助函数来实现setToken调用
        this.setToken(res.data)

        // Toast.success('登录成功')
        this.$toast.success('登录成功')
        this.$router.push('/')
        // 跳转
      } catch {
        // e 错误消息 e不用， (e)可省略不写
        // Toast.fail('登录失败')
        this.$toast.fail('登录失败')
      }
      this.isLoad = false
    }
  }
}
</script>

<style lang="less" scoped></style>
